package com.company.oa.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.oa.meeting.dto.MeetingRoomDTO;
import com.company.oa.meeting.entity.Meeting;
import com.company.oa.meeting.entity.MeetingRoom;
import com.company.oa.meeting.mapper.MeetingMapper;
import com.company.oa.meeting.mapper.MeetingRoomMapper;
import com.company.oa.meeting.service.MeetingRoomService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会议室服务实现类
 */
@Service
public class MeetingRoomServiceImpl extends ServiceImpl<MeetingRoomMapper, MeetingRoom> implements MeetingRoomService {

    @Autowired
    private MeetingMapper meetingMapper;

    @Override
    public IPage<MeetingRoom> getMeetingRoomPage(int page, int size, MeetingRoom meetingRoom) {
        Page<MeetingRoom> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<MeetingRoom> wrapper = new LambdaQueryWrapper<>();
        
        // 设置查询条件
        if (meetingRoom != null) {
            if (StringUtils.hasText(meetingRoom.getName())) {
                wrapper.like(MeetingRoom::getName, meetingRoom.getName());
            }
            if (meetingRoom.getCapacity() != null) {
                wrapper.ge(MeetingRoom::getCapacity, meetingRoom.getCapacity().intValue());
            }
            if (meetingRoom.getStatus() != null) {
                wrapper.eq(MeetingRoom::getStatus, meetingRoom.getStatus());
            }
        }
        
        wrapper.eq(MeetingRoom::getIsDeleted, 0)
               .orderByDesc(MeetingRoom::getCreateTime);
        
        return page(pageParam, wrapper);
    }

    @Override
    @Transactional
    public boolean addMeetingRoom(MeetingRoomDTO meetingRoomDTO) {
        MeetingRoom meetingRoom = new MeetingRoom();
        BeanUtils.copyProperties(meetingRoomDTO, meetingRoom);
        
        // 设置默认值
        meetingRoom.setStatus(meetingRoomDTO.getStatus() != null ? meetingRoomDTO.getStatus() : 1);
        meetingRoom.setCreateTime(LocalDateTime.now());
        meetingRoom.setIsDeleted(0);
        
        return save(meetingRoom);
    }

    @Override
    @Transactional
    public boolean updateMeetingRoom(MeetingRoomDTO meetingRoomDTO) {
        MeetingRoom meetingRoom = getById(meetingRoomDTO.getId());
        if (meetingRoom == null) {
            throw new RuntimeException("会议室不存在");
        }
        
        BeanUtils.copyProperties(meetingRoomDTO, meetingRoom);
        meetingRoom.setUpdateTime(LocalDateTime.now());
        
        return updateById(meetingRoom);
    }

    @Override
    @Transactional
    public boolean deleteMeetingRoom(Long id) {
        // 检查是否有未结束的会议使用该会议室
        LambdaQueryWrapper<Meeting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Meeting::getRoomId, id)
               .in(Meeting::getStatus, 0, 1) // 未开始或进行中
               .eq(Meeting::getIsDeleted, 0);
        
        Long count = meetingMapper.selectCount(wrapper);
        if (count != null && count > 0) {
            throw new RuntimeException("该会议室有未结束的会议，无法删除");
        }
        
        // 逻辑删除
        MeetingRoom meetingRoom = getById(id);
        meetingRoom.setIsDeleted(1);
        meetingRoom.setUpdateTime(LocalDateTime.now());
        
        return updateById(meetingRoom);
    }

    @Override
    public List<MeetingRoom> getAvailableRooms(LocalDateTime startTime, LocalDateTime endTime, Integer capacity) {
        // 获取所有启用的会议室
        LambdaQueryWrapper<MeetingRoom> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingRoom::getStatus, 1)
               .eq(MeetingRoom::getIsDeleted, 0);
        
        if (capacity != null) {
            wrapper.ge(MeetingRoom::getCapacity, capacity);
        }
        
        List<MeetingRoom> allRooms = list(wrapper);
        if (allRooms.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 查询指定时间段内已被占用的会议室ID
        List<Long> roomIds = allRooms.stream().map(MeetingRoom::getId).collect(Collectors.toList());
        List<Long> occupiedRoomIds = new ArrayList<>();
        
        for (Long roomId : roomIds) {
            List<Meeting> meetings = meetingMapper.checkRoomOccupied(roomId, startTime, endTime, null);
            if (!meetings.isEmpty()) {
                occupiedRoomIds.add(roomId);
            }
        }
        
        // 过滤出可用的会议室
        return allRooms.stream()
                .filter(room -> !occupiedRoomIds.contains(room.getId()))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean toggleStatus(Long id) {
        MeetingRoom meetingRoom = getById(id);
        if (meetingRoom == null) {
            throw new RuntimeException("会议室不存在");
        }
        
        // 如果要禁用，检查是否有未结束的会议
        if (meetingRoom.getStatus() == 1) {
            LambdaQueryWrapper<Meeting> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Meeting::getRoomId, id)
                   .in(Meeting::getStatus, 0, 1) // 未开始或进行中
                   .eq(Meeting::getIsDeleted, 0);
            
            Long count = meetingMapper.selectCount(wrapper);
            if (count != null && count > 0) {
                throw new RuntimeException("该会议室有未结束的会议，无法禁用");
            }
        }
        
        // 切换状态
        meetingRoom.setStatus(meetingRoom.getStatus() == 1 ? 0 : 1);
        meetingRoom.setUpdateTime(LocalDateTime.now());
        
        return updateById(meetingRoom);
    }
}